// renderer/utils/request.ts
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'

// 动态等待从 preload 注入的代理地址
const waitApiBase: Promise<string> = (() => {
  const w: any = window as any
  if (w.__API_BASE__) return Promise.resolve(w.__API_BASE__)
  if (typeof w.__whenApiBaseReady === 'function') return w.__whenApiBaseReady()
  return new Promise<string>((resolve) => {
    window.addEventListener(
      'api-base-ready',
      (e: Event) => {
        const detail = (e as CustomEvent).detail
        resolve(detail)
      },
      { once: true }
    )
  })
})()

// 创建 axios 实例
const api: AxiosInstance = axios.create({
  timeout: 10000, // 10 秒超时
})

// 请求拦截器：等待代理地址就绪后再设置 baseURL
api.interceptors.request.use(
  async (config) => {
    const base = await waitApiBase
    if (!config.baseURL) {
      config.baseURL = base
    }
    // 如果需要，也可以在这里附加额外 headers
    // console.log('[Request]', config.method, config.url, '-> base', config.baseURL)
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.status >= 200 && response.status < 300) {
      return response.data
    }
    console.error('[Response Error]', response.status, response.data)
    return Promise.reject(response.data)
  },
  (error) => {
    console.error('[Network Error]', error.message)
    return Promise.reject(error)
  }
)

// 统一导出方法
export function request<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
  return api({
    url,
    method: config?.method || 'GET',
    ...config,
  })
}
